package com.ideal.manage.esms.service.project;

import com.ideal.manage.esms.bean.project.ParamSettingDTO;
import com.ideal.manage.esms.bean.project.UserManageDTO;
import com.ideal.manage.esms.bean.project.VehicleResouceDTO;
import com.ideal.manage.esms.config.shiro.MyShiroRealm;
import com.ideal.manage.esms.repository.framework.MySpecification;
import com.ideal.manage.esms.repository.framework.SpecificationOperator;
import com.ideal.manage.esms.repository.programme.ParamSettingManageRepository;
import com.ideal.manage.esms.repository.programme.SysBrandMakerRepository;
import com.ideal.manage.esms.repository.programme.UserManageRepository;
import com.ideal.manage.esms.repository.programme.VehicleResouceRepository;
import com.ideal.manage.esms.util.HttpRequests;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
public class ShopCarManageService {

    @Autowired
    VehicleResouceRepository vehicleResouceRepository;

    public void deleteById(String id) {
        VehicleResouceDTO byId = vehicleResouceRepository.findById(id);
        byId.setFlag(1);
        vehicleResouceRepository.save(byId);
    }

    public void addShopCar(VehicleResouceDTO dto){
        dto.setCreatetime(new Date());
        dto.setFlag(0);
        Subject subject = SecurityUtils.getSubject();
        MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser)subject.getPrincipal();
        dto.setUserid(shiroUser.getUsername());
        vehicleResouceRepository.save(dto);
    }


    public Page<VehicleResouceDTO> findAllParameterInfos(int pageNum, HttpServletRequest request) {
        List<SpecificationOperator> operators = HttpRequests.getParametersStartingWith(request, "Q_");
        Sort sort = new Sort(Sort.Direction.DESC, "createtime");
        SpecificationOperator operator = new SpecificationOperator("flag", 0, "EQ");
        operators.add(operator);
        for(SpecificationOperator op: operators){
            if(op.getKey().equals("createtime")){
                Date dd = DateUtil.parseYYYYMMDDDate(op.getValue().toString());
                op.setValue(dd);
            }
        }

        MySpecification<VehicleResouceDTO> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 15, sort);
        Page<VehicleResouceDTO> page = vehicleResouceRepository.findAll(mySpecifications, pageable);
        return page;
    }
}
